<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
    <style>
        .slider-bar {
            position: absolute;
            right: 20px;
            top: 300px;
            width: 45px;
            height: 135px;
            background-color: pink;
        }

        .header {
            height: 100px;
            background-color: red;
        }

        .banner {
            height: 250px;
            background-color: orange;
        }

        .content {
            height: 2000px;
            background-color: green;
        }

        span {
            position: absolute;
            bottom: 0;
            display: none;
        }
    </style>
</head>

<body>
    <div class="slider-bar">
        <span class="goBack">返回顶部</span>
    </div>
    <div class="header">头部</div>
    <div class="banner">banner区域</div>
    <div class="content">主题内容</div>

    <script>
        var slider = document.querySelector('.slider-bar');
        var banner = document.querySelector('.banner');

        // 获取banner顶部的距离
        var banner_top = banner.offsetTop;
        // console.log('banner_top===' + banner_top);
        var sliderbar_top = slider.offsetTop - banner_top;
        // console.log('sliderbar_top===' + sliderbar_top);

        var goback = slider.querySelector('.goBack');
        var content = document.querySelector('.content');

        //监听页面滚动事件
        document.addEventListener('scroll', function () {
            //window.pageYOffset: 页面被卷去的头部距离
            if (window.pageYOffset >= sliderbar_top) {
                // 需要把右侧边栏设置成为固定定位
                slider.style.position = 'fixed';
                slider.style.top = sliderbar_top + 'px';
            } else {
                slider.style.position = 'absolute';
                slider.style.top = '300px';
            }

            // 当我们滚动到content的盒子时 goback按钮就显示
            if (window.pageYOffset >= content.offsetTop) {
                goback.style.display = 'block';
            } else {
                goback.style.display = 'none';
            }
        })

        //当我们点击goback时， 我们直接返回顶部
        goback.addEventListener('click', function (event) {
            // 单击返回顶部 页面回到顶部
            scrollTo(0,0);
            // 标准写法： 取消冒泡
            //event.stopPropagation();
            // 停止冒泡事件，IE678之前使用的，但是之后也是可以的
            //event.cancelBubble = true;
        })
    </script>
</body>

</html>